package com.fanco.learn_datastruct_leetcode.juc;
/**
 * @author fanco
 * 一个初始值为0的变量，两个线程对其交替操作，一个加1，一个减1，来5轮。
 * @Desc 生产者消费者模式 1.0版本
 */
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 * 资源类
 */
class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    public void add() throws InterruptedException {
        lock.lock();
        try {
            // 1. 判断 number != 0，防止竟态条件
            while (number != 0) {
                condition.await();
            }
            // 2.干活
            number++;
            System.out.println(Thread.currentThread().getName() + " add 后\t number = " + number);
            // 3. 唤醒其他线程
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void decrement() {
        lock.lock();
        try {
            while (number != 1) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + " decrement \t number=" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public class ProductConsumerDemo_1 {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    shareData.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "线程" + i).start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                shareData.decrement();
            }, "线程" + i).start();
        }
    }
}
